package JaggSoft;

import JaggSoft.Utilidades.*;
import java.awt.*;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.TableRowSorter;
import net.sourceforge.jdatepicker.impl.JDatePickerImpl;

public class ReporteSolicitudes extends javax.swing.JInternalFrame {
    private JDatePickerImpl selector_fecha_inicial,selector_fecha_final;
    private DefaultListModel<ModeloItemValor> modelo = new DefaultListModel<ModeloItemValor>();
    private JCheckBox jchkFechaInicio,jchkFechaFinal;
    private JFileChooser selector;
    public ReporteSolicitudes() {
        initComponents();
        this.setLocation(new Point(70, 0));
        selector=new JFileChooser();
        selector.setFileFilter(new FileNameExtensionFilter("Libro de Excel",new String[]{"xls","xlsx"}));
        selector.setMultiSelectionEnabled(false);
        selector.setSelectedFile(new File("reporte_solicitudes.xls"));
        jlstSolicitantes.setModel(modelo);
        jchkFechaInicio=new JCheckBox("");
        jchkFechaFinal=new JCheckBox("");
        jchkFechaInicio.setToolTipText("Incluir");
        jchkFechaFinal.setToolTipText("Incluir");
        selector_fecha_inicial = Util.ColocarSelectorFecha(jpFechaInicial, null,new Component[]{jchkFechaInicio});
        selector_fecha_final = Util.ColocarSelectorFecha(jpFechaFinal, null,new Component[]{jchkFechaFinal});
        CargarAreas();
        CargarDatos("");
    }
    private void CargarDatos(String filtro){
        String consulta="SELECT s.id_solicitud,a.nombre,CONCAT_WS(' ',so.nombres,so.apellidos) AS nombre_solicitante,so.identidad,so.telefono,"
                + "DATE_FORMAT(s.fecha,'%d/%m/%Y') AS  fecha_solicitud,s.observacion FROM solicitud s INNER JOIN `area` a ON s.id_area=a.id_area "
                + "INNER JOIN solicitante so ON s.id_solicitante=so.id_solicitante"+filtro+";";
        Util.CargarTabla(jtblSolicitudes,consulta,new String[]{"Solicitud","Área","Solicitante","N° Identidad","Teléfono","Fecha de Solicitud","Observación"});
        Util.AlinearColumnas(jtblSolicitudes,SwingConstants.CENTER);
        jtblSolicitudes.setRowSorter(new TableRowSorter<MyModeloTabla>((MyModeloTabla)jtblSolicitudes.getModel()));
    }
    private void CargarDatosDetalle(String id){
        String consulta="SELECT CONCAT_WS(' ',p.nombre,i.unidad_medida,i.detalle) AS producto,b.nombre,ds.cantidad FROM detallesolicitud ds "
                + "INNER JOIN inventario i ON ds.id_inventario=i.id_inventario INNER JOIN producto p ON i.id_producto=p.id_producto "
                + "INNER JOIN bodega b ON ds.id_bodega=b.id_bodega WHERE ds.id_solicitud="+id+" ORDER BY p.nombre,i.unidad_medida,i.detalle;";
        Util.CargarTabla(jtblDetalleSolicitud,consulta,new String[]{"Producto","Bodega","Cantidad"});
        Util.AlinearColumnas(jtblDetalleSolicitud,SwingConstants.CENTER);
        jtblDetalleSolicitud.setRowSorter(new TableRowSorter<MyModeloTabla>((MyModeloTabla) jtblDetalleSolicitud.getModel()));
    }
    private void ConsultaFiltrada(){
        String filtro="";
        filtro=(jlstSolicitantes.getSelectedIndex()>-1?" WHERE so.id_solicitante="+((ModeloItemValor)jlstSolicitantes.getSelectedValue()).getValor():"");
        filtro+=(jcbArea.getSelectedIndex()>-1?(!filtro.equals("")?" AND":" WHERE")+" a.id_area="+((ModeloItemValor)jcbArea.getSelectedItem()).getValor():"");
        if(jchkFechaInicio.isSelected()||jchkFechaFinal.isSelected()){
            SimpleDateFormat formato = new SimpleDateFormat("yyyy/MM/dd");
            if(jchkFechaInicio.isSelected()){
                String fecha_inicial=formato.format((Date)selector_fecha_inicial.getModel().getValue());
                filtro+=(!filtro.equals("")?" AND":" WHERE")+" s.fecha >= '"+fecha_inicial+"'";
            }
            if(jchkFechaFinal.isSelected()){
                String fecha_final=formato.format((Date)selector_fecha_final.getModel().getValue());
                filtro+=(!filtro.equals("")?" AND":" WHERE")+" s.fecha <= '"+fecha_final+"'";
            }
        }
        CargarDatos(filtro);
    }
    private void CargarAreas(){
        jcbArea.removeAllItems();
        Util.CargarJComboBox(jcbArea,"SELECT id_area,nombre FROM `area`",new String[]{"Id","Area"});
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jtfSolicitante = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jlstSolicitantes = new javax.swing.JList();
        jLabel2 = new javax.swing.JLabel();
        jcbArea = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jpFechaInicial = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jpFechaFinal = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtblSolicitudes = new javax.swing.JTable();
        jScrollPane3 = new javax.swing.JScrollPane();
        jtblDetalleSolicitud = new javax.swing.JTable();
        jbtnBuscar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jbtnExportar = new javax.swing.JButton();

        setClosable(true);
        setTitle("Reporte de Solicitudes");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/reporte_solicitudes.png"))); // NOI18N
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentMoved(java.awt.event.ComponentEvent evt) {
                formComponentMoved(evt);
            }
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jLabel1.setText("Solicitante:");

        jtfSolicitante.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtfSolicitanteKeyTyped(evt);
            }
        });

        jScrollPane1.setViewportView(jlstSolicitantes);

        jLabel2.setText("Área/Departamento:");

        jLabel3.setText("Fecha Inicial:");

        javax.swing.GroupLayout jpFechaInicialLayout = new javax.swing.GroupLayout(jpFechaInicial);
        jpFechaInicial.setLayout(jpFechaInicialLayout);
        jpFechaInicialLayout.setHorizontalGroup(
            jpFechaInicialLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 144, Short.MAX_VALUE)
        );
        jpFechaInicialLayout.setVerticalGroup(
            jpFechaInicialLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 20, Short.MAX_VALUE)
        );

        jLabel4.setText("Fecha Final:");

        javax.swing.GroupLayout jpFechaFinalLayout = new javax.swing.GroupLayout(jpFechaFinal);
        jpFechaFinal.setLayout(jpFechaFinalLayout);
        jpFechaFinalLayout.setHorizontalGroup(
            jpFechaFinalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 144, Short.MAX_VALUE)
        );
        jpFechaFinalLayout.setVerticalGroup(
            jpFechaFinalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 20, Short.MAX_VALUE)
        );

        jtblSolicitudes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtblSolicitudesMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(jtblSolicitudes);

        jtblDetalleSolicitud.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane3.setViewportView(jtblDetalleSolicitud);

        jbtnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_buscar_mini.png"))); // NOI18N
        jbtnBuscar.setToolTipText("Buscar");
        jbtnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnBuscarActionPerformed(evt);
            }
        });

        jbtnExportar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/excel.png"))); // NOI18N
        jbtnExportar.setToolTipText("Exportar a Excel");
        jbtnExportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnExportarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jbtnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(jbtnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(46, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jtfSolicitante)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jcbArea, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jbtnBuscar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jLabel3)
                                            .addComponent(jLabel4))
                                        .addGap(18, 18, 18)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jpFechaFinal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(jpFechaInicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))))
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 761, Short.MAX_VALUE)
                    .addComponent(jScrollPane2))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE, false)
                            .addComponent(jLabel1)
                            .addComponent(jtfSolicitante)
                            .addComponent(jLabel2)
                            .addComponent(jcbArea))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3)
                                    .addComponent(jpFechaInicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel4)
                                    .addComponent(jpFechaFinal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jbtnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(15, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void jbtnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnBuscarActionPerformed
        ConsultaFiltrada();
    }//GEN-LAST:event_jbtnBuscarActionPerformed
    private void jtfSolicitanteKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfSolicitanteKeyTyped
        modelo.removeAllElements();
        JTable tabla=Conexion.ObtenerTabla("SELECT id_solicitante,CONCAT_WS(' ',nombres,apellidos) FROM solicitante WHERE nombres LIKE '"+Util.ComponerTexto(jtfSolicitante.getText()+evt.getKeyChar())+"%' OR apellidos LIKE '"+Util.ComponerTexto(jtfSolicitante.getText()+evt.getKeyChar())+"%'",new String[]{"id","solicitante"});
        for (int i = 0; i < tabla.getRowCount(); i++) 
            modelo.addElement(new ModeloItemValor(tabla.getValueAt(i, 1), tabla.getValueAt(i, 0)));
    }//GEN-LAST:event_jtfSolicitanteKeyTyped
    private void formComponentMoved(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentMoved
        if(evt.getComponent().getLocation().x<70)
            evt.getComponent().setLocation(70,evt.getComponent().getLocation().y);
        if(evt.getComponent().getLocation().y<0)
            evt.getComponent().setLocation(evt.getComponent().getLocation().x,0);
    }//GEN-LAST:event_formComponentMoved
    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        if(this.getParent().getWidth()-70<this.getWidth()  && this.isMaximum)
            this.setSize(this.getWidth()-70,this.getHeight());
    }//GEN-LAST:event_formComponentResized
    private void jtblSolicitudesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtblSolicitudesMouseClicked
        if(evt.getClickCount()==2 && !evt.isConsumed())
            CargarDatosDetalle(jtblSolicitudes.getValueAt(jtblSolicitudes.getSelectedRow(),0).toString());
    }//GEN-LAST:event_jtblSolicitudesMouseClicked

    private void jbtnExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnExportarActionPerformed
        if(jtblSolicitudes.getRowCount()>0){
            if(selector.showSaveDialog(null)==JOptionPane.OK_OPTION){
                try {
                    String ruta=selector.getSelectedFile().getAbsolutePath();
                    if(!ruta.endsWith(".xls"))
                        ruta+=".xls";
                    File archivo_excel=new File(ruta);
                    switch(Util.ExportarReporteExcel(jtblSolicitudes,archivo_excel,"Reporte Solicitudes",
                            "SELECT CONCAT_WS(' ',p.nombre,i.unidad_medida,i.detalle) AS producto,b.nombre,ds.cantidad FROM detallesolicitud ds "
                            +"INNER JOIN inventario i ON ds.id_inventario=i.id_inventario INNER JOIN producto p ON i.id_producto=p.id_producto "
                            +"INNER JOIN bodega b ON ds.id_bodega=b.id_bodega WHERE ds.id_solicitud=@id ORDER BY p.nombre,i.unidad_medida,i.detalle;",
                            new String[]{"Producto","Bodega","Cantidad"})){
                        case OK:
                        JOptionPane.showMessageDialog(null,"Archivo Exportado",this.getTitle(),JOptionPane.INFORMATION_MESSAGE);
                        Desktop.getDesktop().open(archivo_excel);
                        break;
                        case CANCELADO:
                        break;
                        case ERROR:
                        JOptionPane.showMessageDialog(null,"No se pudo exportar el archivo","Error",JOptionPane.ERROR_MESSAGE);
                        break;
                    }
                } catch (Exception ex) {System.err.println(ex.getMessage());}
            }
        }
        else
            JOptionPane.showMessageDialog(null,"No hay datos para exportar","Sin Datos",JOptionPane.WARNING_MESSAGE);
    }//GEN-LAST:event_jbtnExportarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JButton jbtnBuscar;
    private javax.swing.JButton jbtnExportar;
    private javax.swing.JComboBox jcbArea;
    private javax.swing.JList jlstSolicitantes;
    private javax.swing.JPanel jpFechaFinal;
    private javax.swing.JPanel jpFechaInicial;
    private javax.swing.JTable jtblDetalleSolicitud;
    private javax.swing.JTable jtblSolicitudes;
    private javax.swing.JTextField jtfSolicitante;
    // End of variables declaration//GEN-END:variables
}